package com.tong.calculator.util;



import com.tong.calculator.exception.FgException;
import com.tong.calculator.response.ResponseCodeConstant;
import com.tong.calculator.valid.EnumValid;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 枚举工具类
 * @author lv
 * @version 1.0.0
 */
public class EnumUtil {

    private EnumUtil(){}

    /**
     * 通过code获取枚举对象
     * @param target 枚举对象
     * @param code code
     * @param <T> 泛型
     * @return 泛型对象
     */
    public static  <T extends Enum<? extends EnumValid>> T getEnumByCode(Class<T> target, String code){
        T[] enumConstants = target.getEnumConstants();
        List<T> baseList = Arrays.stream(enumConstants).filter(t -> Objects.equals(((EnumValid)t).getCode(), code))
                .collect(Collectors.toList());
        Assert.assertNotNull(baseList,"没有匹配的枚举");
        if(baseList.size() > 1){
            throw new FgException(ResponseCodeConstant.PARAM_ERROR, "枚举异常，预计1个枚举匹配，实际"+baseList.size()+"个匹配");
        }
        return baseList.get(0);
    }

    /**
     * 校验指定值是否在目标枚举范围内
     * @param target 目标对象
     * @param code 需要校验的值
     * @param <T> 泛型
     * @return 泛型对象
     */
    public static  <T extends Enum<? extends EnumValid>> boolean isValid(Class<T> target, String code){
        EnumValid[] enumConstants = (EnumValid[]) target.getEnumConstants();
        long count = Arrays.stream(enumConstants).filter(enumValid -> Objects.equals(enumValid.getCode(), code)).count();
        return count == 1;
    }
}
